package org.report.pdf;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author Administrator
 * @describe 说明
 * @date 2024/5/13 0013 9:03
 */
public class PdfUtils {
    public static void main(String[] args) {
        String wordPath = "E:\\study\\report-util\\src\\main\\resources\\word\\test-template.docx";
        String pdfPath = "E:\\study\\report-util\\src\\main\\resources\\word\\pdf.pdf";
        word2Pdf(wordPath, pdfPath);
    }
    public static void word2Pdf(String wordPath, String pdfPath) {
        if (!getLicense()) {
            throw new RuntimeException("未配置许可证!");
        }
        try (FileOutputStream os = new FileOutputStream(pdfPath)) {
            // 要转换的Word文档
            Document doc = new Document(wordPath);
            // 保存为PDF格式
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Aspose的许可证
     * 如果未获取则转换的pdf带有水印
     *
     * @return 是否成功获取许可证
     */
    public static boolean getLicense() {
        boolean result = false;
        // license.xml文件应放在resource路径下
        try (InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream("license.xml");) {
            License license = new License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
